package com.demo.study.creative.d05_singleton;

/**
 * 使用内部类，解决多线程问题
 *
 * @author Baymax
 * @since 2021/1/18
 */
public class PerfectSingleton {
    private static PerfectSingleton instance = null;

    private PerfectSingleton() {
    }

    /* 使用内部类，JVM可以保证实例的唯一性 */
    private static class SingletonFactory {
        private static PerfectSingleton instance = new PerfectSingleton();
    }

    public static PerfectSingleton instance() {
        return SingletonFactory.instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    PerfectSingleton sgt = PerfectSingleton.instance();
                    System.out.println("current task: " + sgt.hashCode());
                }
            }).start();
        }
    }
}
